package com.admin.scroller.photoorvideo.fragment;

import android.arch.lifecycle.Observer;
import android.graphics.Point;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.view.View;

import com.admin.scroller.photoorvideo.adapter.GridBodyAdapter;
import com.admin.scroller.photoorvideo.beans.LocalPhoto;
import com.admin.scroller.photoorvideo.utils.ScreenUtils;

import java.util.List;


/**
 * 已grid界面形式展示照片数据的页面
 */
public class PhotoGrildFragment extends BasePhotoFragment {

    private List<LocalPhoto> localPhotos;
    private GridBodyAdapter bodyAdapter;

    private int allHeight=0;
    private int itemW;
    private int numberCloum=4;

    private GridLayoutManager layoutManager;

    @Override
    void initData(){
        bodyAdapter=new GridBodyAdapter(getActivity());
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),numberCloum));
        recyclerView.setAdapter(bodyAdapter);
        if(viewModel!=null){
            viewModel.getLocalData().observe(this, new Observer<List<LocalPhoto>>() {
                @Override
                public void onChanged(@Nullable List<LocalPhoto> photos) {
                    localPhotos=photos;
                    bodyAdapter.upData(localPhotos);
                    dataSize=localPhotos.size();
                    if(allHeight==0) {
                        getAllHeight();
                    }
                }
            });

        }
    }

    @Override
    public void onResume() {
        super.onResume();
        bodyAdapter.notifyDataSetChanged();
    }

    @Override
    void getAllHeight(){
        Point point=ScreenUtils.getScreenSize(getActivity());
        itemW=point.x/numberCloum;
        int count=localPhotos.size();
        int s=count/numberCloum;
        if(count-s*numberCloum>0){
            s+=1;
        }
        allHeight=s*itemW;
    }

    //列表滑动到的item位置
    @Override
    void getProgress(){
        layoutManager=(GridLayoutManager) recyclerView.getLayoutManager();
        int f=layoutManager.findFirstVisibleItemPosition();
        int itemPosition = f / numberCloum ;
        //因为是相同的Item所以取那个都一样
        View firstVisiableChildView = layoutManager.findViewByPosition(f);
        int itemHeight = firstVisiableChildView.getHeight();
        int itemTop = firstVisiableChildView.getTop();
        int iposition = itemPosition * itemHeight;
        progress = iposition - itemTop;
        if(layoutManager.findLastVisibleItemPosition()==localPhotos.size()-1){
            if(allHeight<progress){
                allHeight=progress;
            }
        }

        if(!onTouchBar){
            int y=(int)(linearBody.getHeight()*progress*1f/allHeight);
            setLinearBarLocation(y);
        }
    }

    @Override
    void changeTextDate(int index) {
        textDate.setText(((LocalPhoto)bodyAdapter.getItem(index)).getData());
    }

}
